package com.srpingde.hhh;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.springde.hhh.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.srpingde.hhh.adapter.TopGridViewAdaPter;
import com.srpingde.hhh.application.HhhApp;
import com.srpingde.hhh.application.HHHDataManage;
import com.srpingde.hhh.bean.GuangGao;
import com.srpingde.hhh.bean.GuangGaoData;
import com.srpingde.hhh.bean.TopBean;
import com.srpingde.hhh.http.AsyncHttpResponseHandler;
import com.srpingde.hhh.jiekou.HHHIml;
import com.srpingde.hhh.jiekou.HHHInterface;
import com.srpingde.hhh.view.MyGridView;

public class TopActivity extends Activity {
	
	private static List<String>  bid = new ArrayList<String>();
	private static List<String>  na = new ArrayList<String>();
	Thread mthread;
	String strtemp;
	Intent in;
	
	static String te;
	
	GuangGao guangGao;
	List<GuangGao> gaos;
	ViewPager viewPager;
	MyGridView gridView;
	HHHIml weiQuIml;
	TextView top_title_tv;
	List<String> url;
	List<String> id;
	TopBean topBean;
	static int indext;
	Timer timer;
	private String tag = "TopActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_top);
		init();
		timer = new Timer();
		getTopDaTa();
		getButtomDaTa();
		layout();
	}

	private void init() {
		indext = 0;
		viewPager = (ViewPager) findViewById(R.id.top_pager);
		gridView = (MyGridView) findViewById(R.id.top_gridview);
		top_title_tv = (TextView) findViewById(R.id.top_title_tv);
		gaos = new ArrayList<GuangGao>();
		url = new ArrayList<String>();
		id = new ArrayList<String>();
		layout();
		weiQuIml = new HHHIml();
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent in = new Intent(TopActivity.this,
						XiangQingActivity.class);
				in.putExtra("id", topBean.getRows().get(arg2).getPid());
				startActivity(in);
			}
		});
	}

	// 获取数据
	private void getTopDaTa() {
		weiQuIml.topGuangGao(TopActivity.this, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				guangGao = HHHDataManage.getInstance().getGuangGao();
				Log.e("mytag", guangGao.getRows().size()
						+ "==================得到的数据的长度" + guangGao.getTotal());				
				viewPager.setAdapter(new TopPagerAdatper(TopActivity.this,
						guangGao.getRows()));
				timer.schedule(new TimerTask() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Integer len;
						len = guangGao.getRows().size();
						Message message = new Message();
						message.what = 2;
						indext = viewPager.getCurrentItem();
						indext = indext % len;
						System.out.println(indext);
						handler.sendMessage(message);
						indext++;
					}
				}, 10000, 10000);
			}
		});
	}

	final Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 2) {
				viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
			}
		}
	};

	private void getButtomDaTa() {
		weiQuIml.bottomGuangGao(TopActivity.this,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						Log.e("mytag", content);
						topBean = HHHDataManage.getInstance().getTopBean();
						gridView.setAdapter(new TopGridViewAdaPter(
								TopActivity.this, topBean.getRows()));
					}
				});

	}

	private void layout() {
		// 头的高度
		LinearLayout.LayoutParams titleLayoutParams = (android.widget.LinearLayout.LayoutParams) top_title_tv
				.getLayoutParams();
		titleLayoutParams.height = HhhApp.getInstance().title_h();
		top_title_tv.setLayoutParams(titleLayoutParams);

		LinearLayout.LayoutParams layoutParams = (LayoutParams) viewPager
				.getLayoutParams();
		layoutParams.height = (int) (HhhApp.getInstance()
				.getDisplayHightAndWightPx()[1] * 0.4);
		viewPager.setLayoutParams(layoutParams);
	}

	class TopPagerAdatper extends PagerAdapter {

		Context context;
		List<GuangGaoData> listKv = new ArrayList<GuangGaoData>();

		public TopPagerAdatper(Context context, List<GuangGaoData> listKv) {
			super();
			this.context = context;
			this.listKv = listKv;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return Integer.MAX_VALUE;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			// TODO Auto-generated method stub
			((ViewPager) container).removeView((View) object);
		}

		// 判断是否由对象生成界面
		@Override
		public boolean isViewFromObject(View v, Object arg1) {
			// TODO Auto-generated method stub
			// Log.i("info","isViewFromObject");
			return v == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			// TODO Auto-generated method stub
			
			final GuangGaoData bean = listKv.get(position % listKv.size());
			final ImageView imageView = new ImageView(context);
			final ImageView kvShow = imageView;
			Log.i("url", HHHInterface.httpHeader + bean.getUrl());
			ImageLoader.getInstance().loadImage(
					HHHInterface.httpHeader + bean.getUrl(),
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap bitmap) {
							BitmapDrawable bitmapDrawable = new BitmapDrawable(
									bitmap);
							kvShow.setImageBitmap(bitmap);
						}
					});
			// Log.e("mytag",
			// listKv.get(position).getHref().substring(5,6)+"===============截取type");
			imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					int t = position;
					t = t % guangGao.getRows().size();
					String tp = listKv.get(t).getHref().substring(5,6);
					strtemp = "type=" + tp + "&id=";
					
					String img = listKv.get(t).getUrl();
					final String nm = listKv.get(t).getName();
					
					String str = bean.getHref();
					int m1 = str.indexOf(strtemp);
					int m2 = str.lastIndexOf("=");
					int m3 = str.length();
					if (m1 < 0)
						return;
					strtemp = str.substring(m2 + 1, m3);
					te = strtemp;
					// if(bean.getHref().length()>=3){
					in = null;
					if(tp.equals("1")){
						in = new Intent(context, XiangQingActivity.class);
						// in.putExtra("id",
						// bean.getHref().substring(bean.getHref().length()-1,bean.getHref().length()));
						in.putExtra("id", strtemp);
						startActivity(in);
					}
					
					if(tp.equals("2")){
						
						Runnable runnable = new Runnable(){
							
							@Override
							public void run(){
								try { 
						            //获取后台返回的Json对象  
									JSONObject mJsonObject = JSONUtil.getJSON(HHHInterface.httpHeader + "api.php?tab=beautypic&act=data&bid=" + strtemp);
							            
							        //JSONObject dataJSON= new JSONObject(mJsonObject.getString("rows"));
							       
							        JSONArray mJsonArray = mJsonObject.getJSONArray("rows");
							        
							        JSONObject clsName = mJsonArray.getJSONObject(0);
							        //资源个数
						            bid.add(clsName.getString("bpic"));
						            
						            na.add(clsName.getString("desc"));
						            
						            in = new Intent(context, HHHMeiTuXiangQing.class);
									// in.putExtra("id",
									// bean.getHref().substring(bean.getHref().length()-1,bean.getHref().length()));
									in.putExtra("id", strtemp);
									in.putExtra("image", bid.get(0).toString());
									in.putExtra("name", na.get(0).toString());
									startActivity(in);
									bid.clear();
									na.clear();
						            
						        } catch (JSONException e) {  
						            e.printStackTrace();
						        } catch (Exception e) {  
						            e.printStackTrace();  
						        }
							}		
						};
						
						mthread = new Thread(runnable);
						mthread.start();
					}
					
					if(tp.equals("3")){
						in = new Intent(context, MeiWenActivity.class);
						// in.putExtra("id",
						// bean.getHref().substring(bean.getHref().length()-1,bean.getHref().length()));
						in.putExtra("aid", strtemp);
						startActivity(in);
					}
					
					// }
				}
			});

			container.addView(imageView);
			return imageView;
		}
	}
}
